package de.preamp.clients.java.utils;

import java.io.IOException;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.json.JSONException;

import de.preamp.clients.java.data.Artist;
import de.preamp.clients.java.net.ServerConnection;
import de.preamp.clients.java.net.ServerConnectionImpl;


/**
 * @author André Stannek
 * @version 2009-08-28
 */
public class Benchmark
{
    /**
     * 
     */
    private static final Logger LOGGER = Logger.getLogger("benchmark");

    /**
     * main method to run all available benchmarks from the console.
     * 
     * @param args
     *            arguments, non taken
     * @throws InterruptedException
     *             if something is wrong
     * @throws IOException
     *             if something is wrong
     * @throws JSONException
     *             if something is wrong
     */
    public static void main(final String[] args) throws InterruptedException,
            JSONException, IOException
    {
        final ServerConnection con = new ServerConnectionImpl();
        final Benchmark bench = new Benchmark();
        bench.benchGetAllArtists(con);
        bench.benchImageCache(con);

    }

    /**
     * Benchmarks how long it takes to request all artist from the preamp
     * server.
     * 
     * @param con
     *            the {@link ServerConnection} used for the benchmark
     * @return the time in milliseconds needed for the request
     * @throws InterruptedException
     *             if something is wrong
     * @throws IOException
     *             if something is wrong
     * @throws JSONException
     *             if something is wrong
     */
    public final long benchGetAllArtists(final ServerConnection con)
            throws InterruptedException, JSONException, IOException
    {
        Collection<Artist> artists;
        LOGGER.log(Level.INFO, "fetching artists");
        final long start = System.nanoTime();
        artists = con.getAllArtists();
        final long end = System.nanoTime();
        final long time = (end - start) / 1000000;
        Thread.sleep(200);
        LOGGER.log(Level.INFO, "fetched " + artists.size() + " artists in "
                + time + "ms");
        return time;
    }

    /**
     * @param con
     *            the {@link ServerConnection} used for the benchmark
     * @return the time in milliseconds needed for the request
     */
    public final long benchImageCache(final ServerConnection con)
    {
        LOGGER.log(Level.INFO, "Loading Images");
        final long start = System.nanoTime();
        final ImageCache cache = ImageCache.instance();
        final long end = System.nanoTime();
        final long time = (end - start) / 1000000;
        LOGGER.log(Level.INFO, "loaded "
                + cache.getArtistImages().keySet().size()
                + " images from file in " + time + "ms");
        return time;
    }
}
